define [
	'jquery'
	'jquery.validate.min'
	'sammy/plugins/sammy.template-0.7.1.min.js'
	'jquery.couch.js'
	'helper'
],($, undef, undef, undef, undef, helper) ->

	S = {}

	$.validator.addMethod( 
		'regex'
		(value, element, regexp) ->
			if regexp.constructor isnt RegExp
				regexp = new RegExp(regexp)
			else if regexp.global
				regexp.lastIndex = 0
			return @optional(element) or regexp.test(value)
		'Format incorrect'
	)
	$.fn.mb_add_donor = (SamCtx) ->
		S = SamCtx
		$this = $(@)
		$tpl = $('.tpl.addDonor > form')
		name = $('input[name="first_name"]').val()
		$('input[name="first_name"]', $this).blur( ()-> 
			if ($(@).val().length is 0)
				$('span.error').remove()
				$(@).focus()
				$(@).after('<span class="error">Please enter:First Name</span>')
			else
				$('span.error').remove()
				$(@).focusout()
		)
		$('input[name="last_name"]', $this).blur( ()-> 
			if ($(@).val().length is 0)
				$('span.error').remove()
				$(@).focus()
				$(@).after('<span class="error">Please enter:Last Name</span>')
			else
				$('span.error').remove()
				$(@).focusout()
		)
		return @ if @mb_plugin()
		@mb_plugin 'add_donor'
		$form = $('form', @)
		$.subscribe(
			'mb.query'
			(e,arg) ->
				donor_type = arg['search_type']
				$edit = $tpl.clone()
				if donor_type is 'org' then $edit.find(".ind").remove()
				else $edit.find(".org").remove()
				$this.find('.content').empty().append $edit.show()
		)
		$this.find('.content form').validate
			rules: 
				'tel_home':
					'required': true
					'regex': /^[2-9]\d{2}-\d{3}-\d{4}$/ 
		$this.find('.content').on "click", "input:submit", ->
			doc1 = $this.find('.content form').serializeObject()
			$.couch.db('vcn-members').saveDoc(
				doc1 
				success: (data) ->
					$.publish 'mb.donor', {donor_id: data.id}
				error: ->
					$.publish 'mb.error', 'Document is not saved'
			)
		return @

	$.fn.serializeObject = () ->
		doc = {}
		a = @serializeArray()
		$.each a,() -> 
			if doc[@name] isnt undefined
				unless doc[@name].push
					doc[@name] = [doc[@name]]
				doc[@name].push(@value or '')
			else 
				doc[@name] = @value or ''
		return doc
	return @


